package com.ruoyi.project.system.movement;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.system.partymember.domain.PartyMember;
import com.ruoyi.project.system.partymember.service.IPartyMemberService;
import com.ruoyi.project.system.dept.service.IDeptService;
import com.ruoyi.project.system.dept.domain.Dept;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;

@Controller
@RequestMapping("/system/movement")
public class MovementController extends BaseController {

    @Autowired
    private IPartyMemberService partyMemberService;
    
    @Autowired
    private IDeptService deptService;

    @RequiresPermissions("system:movement:partyBuildingMap")
    @GetMapping("/partyBuildingMap")
    public String partyBuildingMap() {
        return "system/movement/partyBuildingMap";
    }

    @GetMapping("/partyMemberInfo")
    @RequiresPermissions("system:movement:partyMemberInfo")
    public String partyMemberInfo() {
        return "system/movement/partyMemberInfo";
    }

    @GetMapping("/partyMemberEvaluation")
    @RequiresPermissions("system:movement:partyMemberEvaluation")
    public String partyMemberEvaluation() {
        return "system/movement/partyMemberEvaluation";
    }
    
    /**
     * 获取党员统计信息
     */
    @PostMapping("/getPartyMemberStats")
    @ResponseBody
    public AjaxResult getPartyMemberStats() {
        try {
            Map<String, Object> stats = new HashMap<>();
            
            // 获取所有党员信息
            List<PartyMember> allMembers = partyMemberService.selectPartyMemberList(new PartyMember());
            
            // 统计党员总数
            int totalMembers = allMembers.size();
            
            // 统计党支部数（通过部门统计）
            List<Dept> depts = deptService.selectDeptList(new Dept());
            int totalBranches = (int) depts.stream().filter(dept -> dept.getDeptName().contains("党支部")).count();
            if (totalBranches == 0) {
                totalBranches = 12; // 默认值
            }
            
            // 统计本年度新发展党员（入党时间在今年的）
            LocalDate currentYear = LocalDate.now();
            LocalDate yearStart = currentYear.withDayOfYear(1);
            Date yearStartDate = Date.from(yearStart.atStartOfDay(ZoneId.systemDefault()).toInstant());
            
            int newMembersThisYear = (int) allMembers.stream()
                .filter(member -> member.getJoinPartyDate() != null && 
                        member.getJoinPartyDate().after(yearStartDate))
                .count();
            
            stats.put("totalMembers", totalMembers);
            stats.put("totalBranches", totalBranches);
            stats.put("newMembersThisYear", newMembersThisYear);
            
            return AjaxResult.success(stats);
        } catch (Exception e) {
            return AjaxResult.error("获取统计信息失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取党员信息列表（用于展示面板）
     */
    @PostMapping("/getPartyMemberList")
    @ResponseBody
    public TableDataInfo getPartyMemberList(PartyMember partyMember, String search, String branchFilter, String timeFilter, String positionFilter) {
        try {
            startPage();
            
            // 处理搜索条件
            if (search != null && !search.trim().isEmpty()) {
                partyMember.setName(search.trim());
            }
            
            // 处理支部筛选
            if (branchFilter != null && !branchFilter.trim().isEmpty()) {
                // 根据支部名称查找对应的部门ID
                Dept searchDept = new Dept();
                searchDept.setDeptName(branchFilter);
                List<Dept> depts = deptService.selectDeptList(searchDept);
                if (!depts.isEmpty()) {
                    partyMember.setDeptId(depts.get(0).getDeptId());
                }
            }
            
            // 处理职务筛选
            if (positionFilter != null && !positionFilter.trim().isEmpty()) {
                String position = "";
                switch (positionFilter) {
                    case "1": position = "党委书记"; break;
                    case "2": position = "党委副书记"; break;
                    case "3": position = "组织委员"; break;
                    case "4": position = "宣传委员"; break;
                    case "5": position = "普通党员"; break;
                }
                partyMember.setPartyPost(position);
            }
            
            List<PartyMember> list = partyMemberService.selectPartyMemberList(partyMember);
            
            // 处理时间筛选（在查询结果中过滤）
            if (timeFilter != null && !timeFilter.trim().isEmpty()) {
                LocalDate now = LocalDate.now();
                Date filterDate = null;
                
                switch (timeFilter) {
                    case "1": // 近1年
                        filterDate = Date.from(now.minusYears(1).atStartOfDay(ZoneId.systemDefault()).toInstant());
                        break;
                    case "2": // 近3年
                        filterDate = Date.from(now.minusYears(3).atStartOfDay(ZoneId.systemDefault()).toInstant());
                        break;
                    case "3": // 近5年
                        filterDate = Date.from(now.minusYears(5).atStartOfDay(ZoneId.systemDefault()).toInstant());
                        break;
                    case "4": // 5年以上
                        filterDate = Date.from(now.minusYears(5).atStartOfDay(ZoneId.systemDefault()).toInstant());
                        break;
                }
                
                if (filterDate != null) {
                    final Date finalFilterDate = filterDate;
                    if ("4".equals(timeFilter)) {
                        // 5年以上：入党时间早于5年前
                        list = list.stream()
                            .filter(member -> member.getJoinPartyDate() != null && 
                                    member.getJoinPartyDate().before(finalFilterDate))
                            .collect(java.util.stream.Collectors.toList());
                    } else {
                        // 近几年：入党时间在指定时间之后
                        list = list.stream()
                            .filter(member -> member.getJoinPartyDate() != null && 
                                    member.getJoinPartyDate().after(finalFilterDate))
                            .collect(java.util.stream.Collectors.toList());
                    }
                }
            }
            
            return getDataTable(list);
        } catch (Exception e) {
            return getDataTable(new java.util.ArrayList<>());
        }
    }
    

}
